<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 2] 2.12 Statements</TITLE>
<META NAME="author" CONTENT="David Flanagan">
<META NAME="date" CONTENT="Thu Jul 31 15:48:08 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Java in a Nutshell">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Java in a Nutshell" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch02_11.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 2<br>How Java Differs from C</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch02_13.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="JNUT2-CH-2-SECT-12">2.12 Statements</A></h2>

<P CLASS=para>
<A NAME="STATEMENTS"></A><A NAME="PROGRAMMING-IN-JAVA3"></A>Many of Java's control statements are similar or identical
to C statements.  This section lists and, where necessary,
explains Java's statements.  Note that the topic of
exceptions and the <tt CLASS=literal>try</tt>/<tt CLASS=literal>catch</tt>/<tt CLASS=literal>finally</tt>
statement is substantial enough that it is covered later
in a section of its own.

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-2-SECT-12.1">The if/else, while, and do/while Statements</A></h3>

<P CLASS=para>
The <tt CLASS=literal>if</tt>, <tt CLASS=literal>else</tt>, <tt CLASS=literal>do</tt>, and <tt CLASS=literal>while</tt>
statements are exactly the same in Java as they are in C.
The only substantial difference arises because the Java
<tt CLASS=literal>boolean</tt> type cannot be cast to other types.  In
Java, the values <tt CLASS=literal>0</tt> and <tt CLASS=literal>null</tt> are not the same
as <tt CLASS=literal>false</tt>, and non-zero and non-<tt CLASS=literal>null</tt> values
are not the same as <tt CLASS=literal>true</tt>.

<P CLASS=para>
The conditional expression that is expected by the
<tt CLASS=literal>if</tt>, the <tt CLASS=literal>while</tt>, and the
<tt CLASS=literal>do</tt>/<tt CLASS=literal>while</tt> statements must be of
<tt CLASS=literal>boolean</tt> type in Java.  Specifying an integer type or
a reference type won't do.  Thus, the following C code is
not legal in Java:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
int i = 10;
while(i--) {
    Object o = get_object();
    if (o) {
        do { ... } while(j);
    }
}
</PRE>
</DIV>

<P CLASS=para>
In Java, you must make the condition you are testing for
clear by explictly testing your value against <tt CLASS=literal>0</tt> or 
<tt CLASS=literal>null</tt>.  Use code like the following:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
int i = 10;
while(i-- &gt; 0) {
    Object o = get_object();
    if (o != null) {
        do { ... } while(j != 0);
    }
}
</PRE>
</DIV>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-2-SECT-12.2">The switch Statement</A></h3>

<P CLASS=para>
The <tt CLASS=literal>switch</tt> statement is the same in Java as it is in
C.  You may use <tt CLASS=literal>byte</tt>, <tt CLASS=literal>char</tt>, <tt CLASS=literal>short</tt>,
<tt CLASS=literal>int</tt>, or <tt CLASS=literal>long</tt> types as the values of the
<tt CLASS=literal>case</tt> labels, and you may also specify a
<tt CLASS=literal>default</tt> label just as you do in C.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-2-SECT-12.3">The for Loop</A></h3>

<P CLASS=para>
The <tt CLASS=literal>for</tt> statement is perhaps the most useful looping
construct available in Java.  There are only two differences
between the Java <tt CLASS=literal>for</tt> loop and the C <tt CLASS=literal>for</tt>
loop.  
The first difference is that although Java does not
support the C comma operator (which allows multiple
expressions to be joined into a single expression), the Java
<tt CLASS=literal>for</tt> loop simulates it by allowing multiple comma-separated
expressions to appear in the initialization and increment
sections, but not the test section, of the loop.  For
example:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
int i;
String s;
for(i=0, s = "testing";             // Initialize variables.
    (i &lt; 10) &amp;&amp; (s.length() &gt;= 1);  // Test for continuation.
    i++, s = s.substring(1))        // Increment variables.
{    
    System.out.println(s);          // Loop body.
}
</PRE>
</DIV>

<P CLASS=para>
As you can see, this "difference" between the Java and C
<tt CLASS=literal>for</tt> loops is really a similarity.

<P CLASS=para>
The second difference is the addition of the C++ ability to
declare local loop variables in the initialization section
of the loop:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
for(int i = 0; i &lt; my_array.length; i++) 
    System.out.println("a[" + i + "] = " + my_array[i]);
</PRE>
</DIV>

<P CLASS=para>
Variables declared in this way have the <tt CLASS=literal>for</tt> loop as
their scope. In other words, they are only valid within the body of
the <tt CLASS=literal>for</tt> loop and within the initialization, test,
and increment expressions of the loop. Although variables
declared in <tt CLASS=literal>for</tt> loops have their own scope, the Java
compiler won't let you declare a loop variable that has the
same name as an already existing variable or parameter.

<P CLASS=para>
Note that because variable declaration syntax also uses the
comma, the Java syntax allows you to either specify multiple
comma-separated initialization expressions or to declare and
initialize multiple comma-separated variables of the same
type.  You may not mix variable declarations with other,
non-declaration expressions.  For example, the following
<tt CLASS=literal>for</tt> loop declares and initializes two variables that
are valid only within the <tt CLASS=literal>for</tt> loop.

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
for(int i=0, j=10; i &lt; j; i++, j--) System.out.println("k = " + i*j);
</PRE>
</DIV>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-2-SECT-12.4">Labelled break and continue Statements</A></h3>

<P CLASS=para>
<A NAME="BREAK-STATEMENT"></A><A NAME="CONTINUE-STATEMENT"></A><A NAME="LABELS"></A>The <tt CLASS=literal>break</tt> and <tt CLASS=literal>continue</tt> statements, used
alone, behave the same in Java as they do in C.  However, in
Java, they may optionally be followed by a label that
specifies an enclosing loop (for <tt CLASS=literal>continue</tt>) or any
enclosing statement (for <tt CLASS=literal>break</tt>).  The labelled forms
of these statements allow you to "break" and "continue" any
specified statement or loop within a method definition, not
only the nearest enclosing statements or loop.

<P CLASS=para>
The <tt CLASS=literal>break</tt> statement, without a label, transfers
control out of ("breaks out of" or terminates) the nearest
enclosing <tt CLASS=literal>for</tt>, <tt CLASS=literal>while</tt>, <tt CLASS=literal>do</tt> or
<tt CLASS=literal>switch</tt> statement, exactly as in C.  If the
<tt CLASS=literal>break</tt> keyword is followed by an identifier that is
the label of an arbitrary enclosing statement,
execution transfers out of that enclosing statement.  After
the <tt CLASS=literal>break</tt> statement is executed, any required
<tt CLASS=literal>finally</tt> clauses are executed, and control
resumes at the statement following the terminated statement.
(The <tt CLASS=literal>finally</tt> clause and the <tt CLASS=literal>try</tt> statement
it is associated with are exception handling constructs and
are explained in the next section.) For example:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
test: if (check(i)) {
    try {
        for(int j=0; j &lt; 10; j++) {
            if (j &gt; i) break;           // Terminate just this loop.
            if (a[i][j] == null) 
                break test;             // Do the finally clause and
        }                               // terminate the if statement.
    }
    finally { cleanup(a, i, j); }
}
</PRE>
</DIV>

<P CLASS=para>
Without a label, the <tt CLASS=literal>continue</tt> statement works
exactly as in C: It stops the iteration in progress and
causes execution to resume after the last statement in the
<tt CLASS=literal>while</tt>, <tt CLASS=literal>do</tt>, or <tt CLASS=literal>for</tt> loop, just before
the loop iteration is to begin again.  If the
<tt CLASS=literal>continue</tt> keyword is followed by an identifier that
is the label of an enclosing loop, execution skips to
the end of that loop instead.  If there are any
<tt CLASS=literal>finally</tt> clauses between the <tt CLASS=literal>continue</tt>
statement and the end of
the appropriate loop, these
clauses are executed before control is transferred to the
end of the loop.

<P CLASS=para>
The following code fragment illustrates how the
<tt CLASS=literal>continue</tt> statement works in its labelled and
unlabelled forms.

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
big_loop: while(!done) {
    if (test(a,b) == 0) continue;       // Control goes to point 2.
    try {
        for(int i=0; i &lt; 10; i++) {
            if (a[i] == null) 
                continue;               // Control goes to point 1.
            else if (b[i] == null)
                continue big_loop;      // Control goes to point 2,
                                        // after executing the finally block.
            doit(a[i],b[i]);
           // Point 1.  Increment and start loop again with the test.
        }
    }
    finally { cleanup(a,b); }
    // Point 2.  Start loop again with the (!done) test.
}
</PRE>
</DIV>

<P CLASS=para>
Note the non-intuitive feature of the labelled
<tt CLASS=literal>continue</tt> statement: The loop label must appear at
the top of the loop, but <tt CLASS=literal>continue</tt> causes execution
to transfer to the very bottom of the loop.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-2-SECT-12.5">No goto Statement</A></h3>

<P CLASS=para>
<tt CLASS=literal>goto</tt> is a reserved word in Java, but the
<tt CLASS=literal>goto</tt> statement is not currently part of the language.
Labelled <tt CLASS=literal>break</tt> and <tt CLASS=literal>continue</tt> statements
replace some important and legitimate uses of
<tt CLASS=literal>goto</tt>, and the
<tt CLASS=literal>try</tt>/<tt CLASS=literal>catch</tt>/<tt CLASS=literal>finally</tt> statement replaces
the others.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-2-SECT-12.6">The synchronized Statement</A></h3>

<P CLASS=para>
Since Java is a multithreaded system, care must often be
taken to prevent multiple threads from modifying objects
simultaneously in a way that might leave the object's state
corrupted.  Sections of code that must not be executed
simultaneously are known as "critical sections."  Java
provides the <tt CLASS=literal>synchronized</tt> statement to protect these
critical sections.  The syntax is:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
synchronized (<I CLASS=emphasis>expression</I>) <I CLASS=emphasis>statement</I>
</PRE>
</DIV>

<P CLASS=para>
<I CLASS=emphasis><tt CLASS=literal>expression</tt></I> is an expression that must resolve to an
object or an array.  The <I CLASS=emphasis><tt CLASS=literal>statement</tt></I>
 is the code of
the critical section, which is usually a block of statements
(within <tt CLASS=literal>{</tt> and <tt CLASS=literal>}</tt>).  
The <I CLASS=emphasis><tt CLASS=literal>synchronized</tt></I>
statement attempts to acquire an exclusive lock for the
object or array specified by <tt CLASS=literal>expression</tt>.  It does
not execute the critical section of code until it can obtain
this lock, and in this way, ensures that no other threads
can be executing the section at the same time.

<P CLASS=para>
Note that you do not have to use the <tt CLASS=literal>synchronized</tt>
statement unless your program creates multiple threads that
share data.   If only one thread ever accesses a data
structure, there is no need to protect it with
<tt CLASS=literal>synchronized</tt>.  When you do have to use it, it might
be in code like the following:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
public static void SortIntArray(int[] a) {
    // Sort the array a. This is synchronized so that some other
    // thread can't change elements of the array while we're sorting it.
    // At least not other threads that protect their changes to the
    // array with synchronized.
    synchronized (a) {
        // Do the array sort here. 
    }
}
</PRE>
</DIV>

<P CLASS=para>
The <tt CLASS=literal>synchronized</tt> keyword is more often used as a method
modifier in Java.  When applied to a method, it indicates
that the entire method is a critical section.  For a
<tt CLASS=literal>synchronized</tt> class method (a static method), Java
obtains an exclusive lock on the class before executing the
method.  For a <tt CLASS=literal>synchronized</tt> instance method, Java
obtains an exclusive lock on the class instance.  (Class
methods and instance methods are discussed in the next
chapter.) 

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="JNUT2-CH-2-SECT-12.7">The package and import Statements</A></h3>

<P CLASS=para>
The <tt CLASS=literal>package</tt> statement, as we saw earlier in the
chapter, specifies the package that the classes in a file of
Java source code are part of.  If it appears, it must be the
first statement of a Java file.  The <tt CLASS=literal>import</tt>
statement, which we also saw earlier, allows us to refer to
classes by abbreviated names.  <tt CLASS=literal>import</tt> statements
must appear after the <tt CLASS=literal>package</tt> statement, if any, and
before any other statements in a Java file.  For example:

<P CLASS=para>
<DIV CLASS=screen>
<P>
<PRE>
package games.tetris;
import java.applet.*;
import java.awt.*;
</PRE>
</DIV>

<P CLASS=para>
</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch02_11.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch02_13.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Operators</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Exceptions and Exception Handling</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
